package gro.ecorrdata.edata.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

// import org.springframework.web.bind.annotation.CrossOrigin;
// import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import gro.ecorrdata.edata.model.BaseResponse;
import gro.ecorrdata.edata.util.token.TokenModel;
import gro.ecorrdata.edata.util.token.TokenHelper;
import gro.ecorrdata.edata.controller.UserController;

/**
 * EDataTable
 */
@RestController
@RequestMapping("/table")
public class EDataTableController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserController userController;

    @Autowired
    private TokenHelper tokenHelper;

    @RequestMapping("/list")
    public BaseResponse<Map<String, Object>> getEDataTableList(Integer page) {
        String sqlTotal =  "select count(*) as total from edata_table where isdel=0 ";
        Map<String, Object> result =  jdbcTemplate.queryForMap(sqlTotal);

        String sql = "select id, tableNameEN, tableNameCN,built_name as bname,FROM_UNIXTIME(create_time, '%Y-%m-%d') as ctime,note from edata_table where isdel=0 order by id desc limit "+(page-1)*15+", 15";
        try {
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            result.put("list", list);
            return new BaseResponse<>(true, "查询成功", result);
            
        } catch (Exception e) {
            //TODO: handle exception
            return new BaseResponse<>(true, "查询失败", null);
        }
    }

    @RequestMapping("/gettable")
    public BaseResponse<Map<String, Object>> getEDataTable(Integer id) {


        String sql = "select tableNameEN, tableNameCN,note from edata_table where id=?";
        try {
            Map<String, Object> result = jdbcTemplate.queryForMap(sql, id);
            return new BaseResponse<>(true, "查询成功", result);            
        } catch (Exception e) {
            //TODO: handle exception
            return new BaseResponse<>(true, "查询失败", null);
        }
    }

    @RequestMapping("/update")
    @PostMapping
    public BaseResponse<Object> updateEDataTable(HttpServletRequest request) {
        boolean result = false;
        String id = request.getParameter("id");
        String tableNameEN = request.getParameter("tableNameEN");
        if (tableNameEN==null || tableNameEN== "") {
            return new BaseResponse<>(false, "表名不能为空", null);
        }
        String tableNameCN = (request.getParameter("tableNameCN")==null || request.getParameter("tableNameCN")=="") ? "" : request.getParameter("tableNameCN");
        String note = (request.getParameter("note")==null || request.getParameter("note")=="") ? "" : request.getParameter("note");
        Long ctime = (Long) (System.currentTimeMillis()/1000);
        if (id == null || id=="") {  // 添加
            String authStr = request.getHeader("authStr");
            TokenModel model = tokenHelper.get(authStr);
            Integer userId = model.getUserId();
            // System.out.println(userId);
            Map<String, Object> userInfo = userController.getUserInfoById(userId);
            
            String sql = "INSERT INTO edata_table(tableNameEN, tableNameCN, built_name, create_time, note) VALUES(?,?,?,?,?)";

            int itemp = jdbcTemplate.update(sql,new Object[]{tableNameEN, tableNameCN, userInfo.get("username"), ctime, note});

            if (itemp > 0) {
                result =true;
            }   
        } else {   // 修改
            String sql = "UPDATE edata_table SET tableNameEN=?, tableNameCN=?, note=?, modify_time=?  where `id`=?";

            int itemp = jdbcTemplate.update(sql, new Object[]{tableNameEN, tableNameCN, note, ctime, id});

            if (itemp > 0) {
                result =true;
            }   
        }

        if (result==true) {
            System.out.println("Ok!");
            return new BaseResponse<>(true, "操作成功!", null);
        } else {
            System.out.println("Error!");
            return new BaseResponse<>(false, "操作失败!", null);
        }
    }

    @RequestMapping("/delete")
    @PostMapping
    public BaseResponse<Object> deleteEdata(Integer id) {
        boolean result = false;
        if (id == null) {
            return new BaseResponse<>(false, "找不到要删除的数据", null);
        }

        String sql = "UPDATE edata_table SET `isdel`=1 where `id`=?";
        // System.out.println(sql);
        // System.out.println(id);
        try {
            jdbcTemplate.update(sql, id);
            
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return new BaseResponse<>(result, "操作成功", null);
    }
}